<template>
  <grid-layout :layout="layout" :item-style="{ padding: '15px' }">
    <template #left>
      <split-title> 基础信息</split-title>
      <template v-if="isEventInfo">
        <descriptions :columns="columns.slice(0, 4)" :data-source="eventData" :col-span="24" />
        <descriptions :columns="columns.slice(4)" :data-source="eventData" :col-span="12" />
        <div>
          <span style="color: rgba(255, 255, 255, 0.5)">附件：</span>
          <attachment-list :data-list="eventData.attachment_list" />
        </div>
      </template>
      <descriptions v-else :data-source="details" :columns="columns.slice(-6)" :col-span="24" />
      <!--  高空抛物 -->
      <template v-if="details.field5">
        <split-title text="现场照片" style="margin: 12px 0 10px" />
        <img-viewer :src="details.field5" style="width: 100%; height: 240px" />
      </template>
      <!--  烟感告警 -->
      <template v-if="videoData">
        <split-title style="margin: 12px 0 10px"
          >现场视频<span
            v-if="videoData && videoData.player === 'D0111_1'"
            style="font-size: 0.8em; color: rgba(255, 255, 255, 0.2)"
            >（双击放大视频）</span
          ></split-title
        >
        <div class="video" style="width: 100%; height: 240px; border: 1px solid rgba(255, 255, 255, 0.15)">
          <video-player :data="videoData" />
        </div>
      </template>
    </template>
    <template #center>
      <realtime-msg :data="data" />
    </template>
    <template #right>
      <div style="display: flex; flex-direction: column; height: 100%">
        <split-title style="flex: none; margin: 0 0 10px" text="网格力量实时定位" />
        <base-warn-map
          :single-mode="true"
          :map-options="{
            mapStyle: 'amap://styles/grey',
            features: ['bg', 'point', 'road'],
            viewMode: '2D',
          }"
          style="flex: auto; height: auto; min-height: 0"
          @ready="mapReady"
        >
          <template #default="{ AMap, map }">
            <people-markers :AMap="AMap" :map="map" :center="mapCenter" />
          </template>
        </base-warn-map>
      </div>
    </template>
    <template #bottom>
      <a-space style="flex-wrap: nowrap; justify-content: flex-end; width: 100%">
        <!--        <a-button v-if="isCanSendReport" @click="openDealProcess">社区预处置流程</a-button>-->
        <!--        <a-button @click="videoLink">视频连线</a-button>-->
        <!--        <a-button v-if="details.monitor_id" @click="openVideo">实时视频</a-button>-->
        <a-button v-if="!isEventInfo" @click="msgNotify">短信通知</a-button>
        <a-button v-if="!isEventInfo && !details.relation_id" @click="() => handleWarn(1)">转成事件并指派</a-button>
        <!--        <a-button v-if="details.status != 0" @click="setInvalid">无效</a-button>-->
        <!--        <a-button v-if="isCanSendReport" @click="sendReport('初报')">初报</a-button>-->
        <!--        <a-button v-if="isCanSendReport" @click="sendReport('续报')">续报</a-button>-->
        <!-- 事件的处理类型 -->
        <template v-if="eventData.handle_state == 1 || eventData.handle_state == 2">
          <a-button @click="handleEvent('事件指派', 1)">指派</a-button>
          <a-button @click="handleEvent('事件上报', 2)">上报</a-button>
          <a-button @click="handleEvent('事件办结', 3)">办结</a-button>
        </template>
        <template v-if="eventData.handle_state == 1">
          <a-button @click="handleEvent('事件无效', 4)">无效</a-button>
        </template>
        <template v-if="eventData.handle_state == 3">
          <a-button @click="handleEvent('事件办结', 3)">办结</a-button>
        </template>
      </a-space>
    </template>
  </grid-layout>
</template>

<script>
import BaseWarnMap from '../../amap/map-core-normal.vue';
import GridLayout from '@gis/lib/layouts/grid-layout.vue';
import VideoPlayer from '@gis/lib/components/player/index.jsx';
import ImgViewer from '@gis/lib/components/img-viewer/ImgViewer.vue';
import RealtimeMsg from './realtime-msg.vue';
import BaseMap from '@gis/lib/components/AMap/map-core.vue';
import AttachmentList from '@gis/lib/components/attachment-list.vue';
import { dialog } from '@gis/lib/components/antd-dialog';
import { showVideoConferencingDialog } from '@gis/lib/components/tx-webrtc';
import { openMsgNotifyDialog } from '../msg-notify.jsx';
// import { openReportSendDialog } from '../send-report.jsx';
import PeopleMarkers from './people-markers.vue';
import get from 'lodash-es/get.js';
import isEmpty from 'lodash-es/isEmpty.js';
import { alarmDevDetails, getEventInfoDetail, plentyEngineeringDetail, setWarnInvalid } from '@gis/lib/api';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';
import SplitTitle from '@gis/lib/components/splitter/split-title.vue';
import { h } from 'vue';
import { openMsgWarnHandleDialog } from '../../../views/alarm/msg-warn-handle.js';
import { openEventHandleDialog } from '../../../views/event-manage/event-opt.js';

export default {
  name: 'warn-yangan-dialog',
  components: {
    BaseWarnMap,
    SplitTitle,
    PeopleMarkers,
    AttachmentList,
    RealtimeMsg,
    GridLayout,
    VideoPlayer,
    ImgViewer,
    BaseMap,
  },
  props: {
    data: { type: Object, default: () => ({}) },
  },
  data() {
    return {
      columns: [
        { label: '描述', key: 'event_describe' },
        { label: '事发时间', key: 'occur_time' },
        { label: '处置截止时间', key: 'deadline' },
        { label: '地点', key: 'location' },
        { label: '类别', key: 'p_type_name' },
        { label: '预警类型', key: 'warn_type' },
        { label: '预警联系人', key: 'report_person_name' },
        { label: '联系电话', key: 'report_person_phone' },
        { label: '预警来源', key: 'source' },
        { label: '受理人', key: 'receiver_name_str' },
        { label: '告警类型', key: 'warn_type_name' },
        { label: '告警时间', key: 'warn_time' },
        { label: '告警地点', key: 'warn_place' },
        { label: '告警设备序列号', key: 'field1' },
        { label: '告警设备名称', key: 'field2' },
        { label: '告警内容', key: 'warn_content' },
      ],
      layout: [
        { name: 'left', colSpan: 7 },
        { name: 'center', colSpan: 7 },
        { name: 'right', colSpan: 10 },
      ],
      monitor_id: '',
      details: {},
      eventData: {},
      timeLineList: [],
      mapCenter: [],
      videoData: null,
    };
  },
  computed: {
    // D0137 消息类型
    // D0137_3_4_3烟感 D0137_3_4_10高空抛物
    isCanSendReport() {
      return this.data.fine_type == 'D0137_3_4_3';
    },
    isEventInfo() {
      if (this.data && this.data.isEvent === true) {
        return true;
      }
      /* relation_type: 1 事件, 2 指令, 3 任务 */
      if (this.details.relation_type == 1) {
        return true;
      }
      return false;
    },
  },
  async created() {
    await this.getDataAsync();
    this.getVideoInfoAsync();
  },
  methods: {
    mapReady() {},
    async getDataAsync() {
      const { id, isEvent } = this.data || {};
      if (isEvent === true) {
        await this.getEventDataAsync(id);
      } else {
        this.details = this.handleCommonResult(await alarmDevDetails({ id }), { defaultValue: {} });
        this.mapCenter = [this.details.longitude, this.details.latitude];
        this.monitor_id = this.details.field7;

        /* relation_type: 1 事件, 2 指令, 3 任务 */
        if (this.details.relation_type == 1 && this.details.relation_id) {
          await this.getEventDataAsync(this.details.relation_id);
        }
      }
    },
    async getVideoInfoAsync() {
      if (this.monitor_id) {
        const videoData = this.handleCommonResult(
          await plentyEngineeringDetail({
            monitor_id: this.monitor_id,
          }),
          { defaultValue: {} }
        );
        if (isEmpty(videoData)) {
          this.$message.error('未获取到可用的视频配置信息');
        }
        this.videoData = videoData;
      }
    },
    async getEventDataAsync(event_id) {
      const { area_code } = useUserInfoStore();
      const params = {
        area_code: area_code,
        event_id: event_id,
      };
      const res = await getEventInfoDetail(params);
      const data = (res && res.data) || {};
      const person_list = data.person_list || [];
      const record_list = data.record_list || [];
      this.eventData = Object.assign({}, data, {
        event_id: event_id,
        record_list: data.record_list || [],
        receiver_name_str: person_list.map((item) => `${item.receiver_name}`).join(','),
        attachment_list: record_list.reduce((res, item) => {
          if (!Array.isArray(item.attachment_list)) {
            return res;
          }
          return res.concat(item.attachment_list);
        }, []),
      });
      this.mapCenter = [this.eventData.longitude, this.eventData.latitude];
    },
    openDealProcess() {
      dialog({
        content: {
          name: 'DealProcess',
          render() {
            return h('img', { style: { width: '100%' }, attrs: { src: import('../assets/sqczlc.png') } });
          },
        },
        dialogProps: { title: '社区预处置流程', footer: null, width: 'medium', height: 'fixed' },
      });
    },
    videoLink() {
      showVideoConferencingDialog();
    },
    msgNotify() {
      openMsgNotifyDialog({
        msg: this.details.device_name + this.details.warn_type_name + ',告警时间:' + this.details.warn_time,
      });
    },
    setInvalid() {
      this.$confirm({
        title: (h) => h('div', { style: { color: '#ffffff' } }, '提示'),
        content: (h) => h('div', { style: { color: '#ffffff' } }, '确认将该报警数据设置为无效吗？'),
        centered: true,
        onOk: async () => {
          const { id } = this.data || {};
          return this.handleFormResult(await setWarnInvalid({ id }), {
            onOk: () => {
              this.$set(this.details, 'status', 0);
            },
          });
        },
      });
    },
    sendReport(type) {
      const { id } = this.data || {};
      // openReportSendDialog({ warn_id: id, type });
    },
    handleWarn(type) {
      openMsgWarnHandleDialog(
        {
          mode: { 1: '指派', 4: '无效' }[type],
          data: this.details,
          extraParams: {
            c_type_id: this.details.c_type_id,
            p_type_id: this.details.p_type_id,
          },
          // 请求成功之后,接口返回event_id,请求事件详情
          onAssignSuccess: (val) => {
            const event_id = get(val, 'data', '');
            // this.details = Object.assign({}, this.details, {
            //   event_id: event_id,
            //   relation_id: event_id,
            // });
            this.getEventDataAsync(event_id);
          },
        },
        {
          title: { 1: '转为事件并指派', 4: '标记为无效' }[type],
        }
      ).then((res) => {});
    },
    handleEvent(title, type) {
      openEventHandleDialog(
        {
          type,
          event_id: this.eventData.event_id,
          onHandleSuccess: () => {
            //刷新详情
          },
        },
        { title: title }
      );
    },
  },
};
</script>

<style scoped lang="less">
.video {
  > div {
    height: 240px !important;
  }
}
</style>
